package com.travel.api.controller.user

import com.lgy.sell.controller.BaseController
import com.travel.api.beans.request.BaseRequest
import com.travel.api.beans.request.message.SMSRequest
import com.travel.api.beans.request.user.LoginRequest
import com.travel.api.beans.request.user.RegisterRequest
import com.travel.api.service.message.MessageService
import com.travel.api.utils.ResultConstant
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.*

/**
 * @ClassName 用户Controller
 * @Author liguangyao
 * @Date 13/8/18 下午1:41
 * @Version 1.0
 */
@Api(value = "/user/user", description = "用户")
@RestController
@RequestMapping("user/user")
@CrossOrigin
class UserController : BaseController() {

    @Autowired
    private val messageService: MessageService? = null

    @ApiOperation(value = "用户数据列表", httpMethod = "POST", notes = "用户数据列表")
    @PostMapping("/list")
    fun list(@RequestBody request: BaseRequest): Map<String, Any> {
        val pageInfo = userService!!.list(request)
        return success(null, pageInfo)
    }

    @ApiOperation(value = "用户登录", httpMethod = "POST", notes = "用户登录")
    @PostMapping("/login")
    fun login(@RequestBody request: LoginRequest): Map<String, Any> {
        return userService!!.login(request, httpServletRequest)
    }

    @ApiOperation(value = "用户注册", httpMethod = "POST", notes = "验证码正确并用户注册")
    @PostMapping("/register")
    fun register(@RequestBody request: RegisterRequest): Map<String, Any>? {
        val emailRequest = SMSRequest()
        emailRequest.mobile = request.mobile
        emailRequest.code = request.code
        val result = messageService!!.validationSMS(emailRequest)
        // 验证正确
        return if (!StringUtils.isEmpty(result) && result["code"].toString() == ResultConstant.SUCCESS_RESULT_CODE.toString()) {
            // 调用用户注册接口
            userService!!.register(request)
        } else result
    }

    @ApiOperation(value = "检查Token有效性", httpMethod = "GET", notes = "检查Token有效性 true 为已经失效 false 为未失效")
    @GetMapping("/judgeToken")
    fun judgeToken(@RequestHeader("token") token: String): Boolean {
        return userService!!.judgeToken(token)
    }

    @ApiOperation(value = "获取用户信息", httpMethod = "GET", notes = "根据Token获取用户信息")
    @GetMapping("/userInfo")
    fun userInfo(@RequestHeader("token") token: String): Map<String, Any> {
        val userInfo = userInfo()
        if (StringUtils.isEmpty(userInfo)) {
            fail("没有该用户信息")
        }
        // 用户敏感信息过滤
        userInfo!!.password = "**************"
        return success(null, userInfo)
    }

    @ApiOperation(value = "用户退出", httpMethod = "GET", notes = "用户退出")
    @GetMapping("/logout")
    fun logout(@RequestHeader("token") token: String): Map<String, Any> {
        return if (userService!!.logout(token)) success() else fail("操作失败")
    }
}